package com.aspire.aimini.repository;

import com.aspire.aimini.model.entity.ExportTask;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 导出任务数据访问层
 *
 * @author wangguiyou
 * @date 2024-12-19
 */
@Mapper
public interface ExportTaskRepository extends BaseMapper<ExportTask> {

    /**
     * 分页查询用户的导出任务
     */
    @Select("SELECT * FROM export_task WHERE user_id = #{userId} AND is_deleted = 0 ORDER BY create_time DESC")
    IPage<ExportTask> selectUserTasksPage(Page<ExportTask> page, @Param("userId") Long userId);

    /**
     * 根据状态查询导出任务
     */
    @Select("SELECT * FROM export_task WHERE status = #{status} AND is_deleted = 0 ORDER BY priority DESC, create_time ASC")
    List<ExportTask> selectByStatus(@Param("status") String status);

    /**
     * 查询过期的导出任务
     */
    @Select("SELECT * FROM export_task WHERE expire_time < #{now} AND status = 'completed' AND is_deleted = 0")
    List<ExportTask> selectExpiredTasks(@Param("now") LocalDateTime now);

    /**
     * 查询用户在指定时间范围内的导出任务数量
     */
    @Select("SELECT COUNT(*) FROM export_task WHERE user_id = #{userId} AND create_time >= #{startTime} AND create_time <= #{endTime} AND is_deleted = 0")
    Long countUserTasksInTimeRange(@Param("userId") Long userId, @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);

    /**
     * 查询用户正在进行的导出任务数量
     */
    @Select("SELECT COUNT(*) FROM export_task WHERE user_id = #{userId} AND status IN ('pending', 'processing') AND is_deleted = 0")
    Long countUserActiveTasks(@Param("userId") Long userId);

    /**
     * 更新任务状态和进度
     */
    @Update("UPDATE export_task SET status = #{status}, progress = #{progress}, update_time = NOW() WHERE id = #{id}")
    int updateStatusAndProgress(@Param("id") String id, @Param("status") String status,
            @Param("progress") Integer progress);

    /**
     * 更新任务错误信息
     */
    @Update("UPDATE export_task SET status = 'failed', error_message = #{errorMessage}, end_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int updateErrorMessage(@Param("id") String id, @Param("errorMessage") String errorMessage);

    /**
     * 完成任务
     */
    @Update("UPDATE export_task SET status = 'completed', progress = 100, file_path = #{filePath}, file_size = #{fileSize}, download_url = #{downloadUrl}, end_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int completeTask(@Param("id") String id, @Param("filePath") String filePath, @Param("fileSize") Long fileSize,
            @Param("downloadUrl") String downloadUrl);

    /**
     * 取消任务
     */
    @Update("UPDATE export_task SET status = 'cancelled', end_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int cancelTask(@Param("id") String id);

    /**
     * 增加重试次数
     */
    @Update("UPDATE export_task SET retry_count = COALESCE(retry_count, 0) + 1, status = 'pending', update_time = NOW() WHERE id = #{id}")
    int incrementRetryCount(@Param("id") String id);

    /**
     * 更新任务优先级
     */
    @Update("UPDATE export_task SET priority = #{priority}, update_time = NOW() WHERE id = #{id}")
    int updatePriority(@Param("id") String id, @Param("priority") Integer priority);

    /**
     * 开始处理任务
     */
    @Update("UPDATE export_task SET status = 'processing', start_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int startProcessing(@Param("id") String id);

    /**
     * 暂停任务
     */
    @Update("UPDATE export_task SET status = 'pending', update_time = NOW() WHERE id = #{id}")
    int pauseTask(@Param("id") String id);

    /**
     * 恢复任务
     */
    @Update("UPDATE export_task SET status = 'pending', update_time = NOW() WHERE id = #{id} AND status = 'pending'")
    int resumeTask(@Param("id") String id);

    /**
     * 批量删除任务
     */
    @Update("UPDATE export_task SET is_deleted = 1, update_time = NOW() WHERE id IN (${taskIds}) AND user_id = #{userId}")
    int batchDeleteTasks(@Param("taskIds") String taskIds, @Param("userId") Long userId);

    /**
     * 统计各状态的任务数量
     */
    @Select("SELECT status, COUNT(*) as count FROM export_task WHERE user_id = #{userId} AND is_deleted = 0 GROUP BY status")
    List<Map<String, Object>> countTasksByStatus(@Param("userId") Long userId);

    /**
     * 统计各数据类型的任务数量
     */
    @Select("SELECT data_type, COUNT(*) as count FROM export_task WHERE user_id = #{userId} AND is_deleted = 0 GROUP BY data_type")
    List<Map<String, Object>> countTasksByDataType(@Param("userId") Long userId);

    /**
     * 统计各格式的任务数量
     */
    @Select("SELECT format, COUNT(*) as count FROM export_task WHERE user_id = #{userId} AND is_deleted = 0 GROUP BY format")
    List<Map<String, Object>> countTasksByFormat(@Param("userId") Long userId);

    /**
     * 查询用户的导出配额使用情况
     */
    @Select("SELECT COUNT(*) as daily_count, COALESCE(SUM(file_size), 0) as daily_size FROM export_task WHERE user_id = #{userId} AND DATE(create_time) = CURDATE() AND is_deleted = 0")
    Map<String, Object> getUserDailyQuotaUsage(@Param("userId") Long userId);

    /**
     * 查询系统导出任务统计
     */
    @Select("SELECT status, COUNT(*) as count FROM export_task WHERE is_deleted = 0 GROUP BY status")
    List<Map<String, Object>> getSystemTaskStatistics();

    /**
     * 查询最近的导出任务
     */
    @Select("SELECT * FROM export_task WHERE user_id = #{userId} AND is_deleted = 0 ORDER BY create_time DESC LIMIT #{limit}")
    List<ExportTask> selectRecentTasks(@Param("userId") Long userId, @Param("limit") Integer limit);

    /**
     * 查询可重试的失败任务
     */
    @Select("SELECT * FROM export_task WHERE status = 'failed' AND (retry_count IS NULL OR retry_count < max_retry_count) AND is_deleted = 0 ORDER BY priority DESC, create_time ASC")
    List<ExportTask> selectRetryableTasks();

    /**
     * 查询长时间运行的任务
     */
    @Select("SELECT * FROM export_task WHERE status = 'processing' AND start_time < #{threshold} AND is_deleted = 0")
    List<ExportTask> selectLongRunningTasks(@Param("threshold") LocalDateTime threshold);

    /**
     * 更新处理进度
     */
    @Update("UPDATE export_task SET processed_count = #{processedCount}, total_count = #{totalCount}, progress = #{progress}, update_time = NOW() WHERE id = #{id}")
    int updateProgress(@Param("id") String id, @Param("processedCount") Long processedCount,
            @Param("totalCount") Long totalCount, @Param("progress") Integer progress);

    /**
     * 清理过期文件记录
     */
    @Update("UPDATE export_task SET file_path = NULL, download_url = NULL, update_time = NOW() WHERE expire_time < #{now} AND status = 'completed' AND is_deleted = 0")
    int cleanExpiredFiles(@Param("now") LocalDateTime now);

    /**
     * 查询需要清理的文件路径
     */
    @Select("SELECT file_path FROM export_task WHERE expire_time < #{now} AND status = 'completed' AND file_path IS NOT NULL AND is_deleted = 0")
    List<String> selectExpiredFilePaths(@Param("now") LocalDateTime now);
}